package cn.acheng1314.springboot2.service.impl

import cn.acheng1314.exceptions.EnterInfoErrorException
import cn.acheng1314.exceptions.ForbiddenException
import cn.acheng1314.exceptions.NotFoundException
import cn.acheng1314.exceptions.UnauthorizedException
import cn.acheng1314.springboot2.entity.AdminUser
import cn.acheng1314.springboot2.mapper.AdminUserMapper
import cn.acheng1314.utils.EncryptUtils
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import org.apache.commons.lang3.StringUtils
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.*


/**
 * Created by pc on 2017/8/11.
 */
@Service("userService")
open class AdminUserServiceImpl : ServiceImpl<AdminUserMapper, AdminUser>() {

    @Transactional
    @Throws(Exception::class)
    open fun addOneUser(entity: AdminUser) {
        if (StringUtils.isAnyBlank(entity.loginName, entity.password))
            throw Exception("用户名或密码不能为空！")
        //创建插入时间
        val createTime = Calendar.getInstance(Locale.CHINESE).time
        entity.createDate = createTime
        //MD5密码加盐后再sha256加密
        entity.password = EncryptUtils.encryptPassword(entity.password!!.toLowerCase(), createTime!!.toString())
        entity.isUsed = true   //默认可用
        baseMapper.addUser(entity)
    }

    @Transactional
    @Throws(EnterInfoErrorException::class, NotFoundException::class)
    open fun login(userLogin: String, userPass: String): AdminUser {
        var userPass = userPass
        if (StringUtils.isEmpty(userLogin) || StringUtils.isEmpty(userPass)) {
            throw UnauthorizedException("用户名和密码不能为空！请检查！")
        }
        var result: AdminUser? = null
        result = findOneById(userLogin)
        if (null == result) throw NotFoundException("用户未找到！")
        if (!result.isUsed) throw ForbiddenException("用户禁止登陆！")
        try {
            userPass = userPass.toLowerCase()  //将大写md5转换为小写md5
            if (userPass.length > 16 && userPass.length == 32) {    //32位小写转换为16位小写
                userPass = userPass.substring(8, 24).toLowerCase()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw UnauthorizedException("密码错误！")
        }

        val encryptPassword = EncryptUtils.encryptPassword(userPass, result.createDate!!.toString())

        if (encryptPassword != result.password) {
            throw UnauthorizedException("用户名和密码不匹配！")
        }
        return result
    }

    @Transactional
    open fun findOneById(userLogin: String): AdminUser? {
        return baseMapper.findOneByKey(userLogin)
    }

    fun selectList(): List<AdminUser>? {
        return baseMapper.findAll()
    }

    fun delUser(loginName: String) {
        baseMapper.delUser(loginName)
    }


}
